/* The MIT License (MIT)

	Copyright (c) 2013 Schpitt <schpitt@gmail.com>
	https://code.google.com/p/updator/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE. */

#include "Downloader.h"

#include "Updator.h"
#include "Logger.h"
#include "Utils.h"


#define TCP_ARTIFICIAL_SLOW 0

const unsigned int TCP_BUFFER_MAX_SIZE = 8192;

using namespace std;
using namespace sf;


namespace Updator 
{

Downloader::Downloader( const string& p_host, const string& p_folder, unsigned short p_port ) :
	stopped(false),
	port(p_port),
	host(p_host),
	folder(p_folder),
	listener(0)
{ 
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Downloader::~Downloader()
{
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void Downloader::setListener(Updator* p_listener)
{
	listener = p_listener;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::getData( const string& p_uri, char** p_out_buffer, unsigned int* p_out_size )
{
	if( sock.getRemoteAddress() == sf::IpAddress::None )
		connect();

	if( sock.getRemoteAddress() != sf::IpAddress::None && !stopped ) {
		string    request;
		char*          buffer = 0;
		unsigned int   position = 0;
		unsigned int   length = 0;
		unsigned int   data_len = 0;

		request += "GET http://" + Utils::urlencode(host + folder + "/" + p_uri) + " HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n";
		
		if( !send( request.c_str(), request.size() ) || stopped ) {
			LOG("[down] request not sent");
			disconnect();
			return false;
		}

		if( !getHTTPHeader( &data_len ) || stopped ) {
			disconnect();
			return false;
		}

		buffer = (char*)malloc( data_len );
		if(!buffer || stopped ) { 
			disconnect();
			return false;
		}

		while( !stopped ) {
			if( !receive(buffer+position, data_len - position, &length) )
				break;

			position += length;
#if TCP_ARTIFICIAL_SLOW
			sf::Sleep(0.2f);
#endif
			if( position == data_len )
				break;
		}

		if(stopped == true) {
			free(buffer);
			return false;
		}

		*p_out_buffer = buffer;
		*p_out_size = position;

		return position == data_len;

	} else {
		LOG("[down] can't connect");
	}

	return false;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::getData( const string& p_uri, string& p_out_string )
{
	if( !assureConnection() )
		return false;

	string       request;
	char         buffer[TCP_BUFFER_MAX_SIZE+1];
	unsigned int position = 0;
	unsigned int length = 0;
	unsigned int data_len = 0;

	request += "GET http://" + Utils::urlencode(host + folder + "/" + p_uri) + " HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n";
		
	if( !send( request.c_str(), request.size() ) || stopped ) {
		LOG("[down] request not sent");
		disconnect();
		return false;
	}

	if( !getHTTPHeader( &data_len ) || stopped ) {
		disconnect();
		return false;
	}
		
	while( !stopped ) {
		memset(buffer,0,sizeof(buffer));
		if( !receive(buffer, (data_len - position)>TCP_BUFFER_MAX_SIZE?TCP_BUFFER_MAX_SIZE:(data_len - position), &length) )
			break;

		p_out_string.append(buffer);
		position += length;

#if TCP_ARTIFICIAL_SLOW
		sf::Sleep(0.2f);
#endif
		if( position == data_len )
			break;
	}

	if(stopped == true) {
		return false;
	}

	sock.disconnect();

	return position == data_len;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::getFile( const string& p_filename )
{
	if( !assureConnection() )
		return false;

	string request;
	char buffer[TCP_BUFFER_MAX_SIZE];
	unsigned int length = 0;
	unsigned int received_len = 0;
	unsigned int data_len = 0;
	FILE * file;
		
	request += "GET http://" + Utils::urlencode(host + folder + "/" + p_filename) + " HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n";
		
	if( !send( request.c_str(), request.size() ) || stopped ) {
		LOG("[down] request not sent");
		disconnect();
		return false;
	}

	if( !getHTTPHeader( &data_len ) || stopped ) {
		LOG("[down] header not received");
		disconnect();
		return false;
	}
		
	file = fopen( p_filename.c_str(), "wb+" );
	if( !file ) {
		LOG("[down] file not open [" << p_filename.c_str() << "]");
		return false;
	}
		
	while( !stopped ) {
		memset(buffer, 0, sizeof(buffer));
		if( !receive(buffer, sizeof(buffer), &length) ) {
			LOG("[down] receive failed");
			break;
		}

		fwrite(buffer , 1 , length, file );

		received_len += length;

		if(listener!=0) listener->downloadProgress(length);

#if TCP_ARTIFICIAL_SLOW
		sf::Sleep(0.2f);
#endif

		if(data_len == received_len)
			break;
	}
		
	fclose (file);
		
	if(stopped == true)
		return false;

	sock.disconnect();

	return data_len == received_len;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::getHTTPHeader( unsigned int* p_out_size ) 
{
	if( !assureConnection() )
		return false;

	char header[1024];
	unsigned int position = 0;
	unsigned int length = 0;

	memset(header, 0, sizeof(header));

	while( !stopped ) {
		if( !receive(header+position, 1, &length) )
			return false;

		++position;

		if( strstr(header, "\r\n\r\n") )
			break;
	}

	//printf("header : [%s]\r\n", header);

	if(stopped == true || strstr( header, "404 Not Found" ) != 0 )
		return false;

	char* begin_size = strstr( header, "Content-Length: " ) + strlen("Content-Length: ");
	char* end_size = strstr( begin_size, "\r\n");

	if( !begin_size || !end_size )
		return false;

	// fugly
	char temp[16];
	memset(temp,0,16);
	memcpy(temp, begin_size, end_size - begin_size);

	*p_out_size = atoi(temp);
	
	return true;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::connect()
{	
	LOG("[down] connecting to " << host.c_str() << ":" << port << "...");
	
	if( Socket::Done != sock.connect(host, port)) {
		LOG("[down] connection failed");
		return false;
	} else {
		LOG("[down] connection success");
		stopped = false;
		return true;
	}
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void Downloader::disconnect()
{
	stopped = true;
	sock.disconnect();
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::receive(char* p_buffer, int max, unsigned int* p_length)
{
	if( !assureConnection() )
		return false;

	size_t			received = 0;
	Socket::Status	status;

	status = sock.receive( p_buffer, max, received );

	switch( status ) {
		case Socket::Done:
			*p_length = received;
			return true;
		case Socket::NotReady:
			LOG("[down] not ready");
			return false;
		case Socket::Error:
			LOG("[down] error");
			return false;
		case Socket::Disconnected:
			LOG("[down] disconnected");
			return false;

		default:
			return false;
	}
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::send(const char* p_buffer, unsigned short p_length)
{
	if( !assureConnection() )
		return false;
	
	return Socket::Done == sock.send(p_buffer, p_length);
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::assureConnection()
{
	if( !isConnected() )
		return connect();
	return true;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool Downloader::isConnected()
{
	return sock.getRemoteAddress() != sf::IpAddress::None;
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

} // namespace Updator
